package com.itttq.im.ws.netty;

import com.itttq.im.common.constant.Constant;
import com.itttq.im.common.constant.RedisConstant;
import com.itttq.im.conf.WsProperties;
import com.itttq.im.utils.RedisUtil;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.stream.ChunkedWriteHandler;
import io.netty.handler.timeout.IdleStateHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.net.InetSocketAddress;
import java.util.concurrent.TimeUnit;

/**
 * Netty服务主类
 *
 * @Author GXG
 */
@Slf4j
@Component
public class NettyServer implements Runnable {
    @Autowired
    private WsServerHandler wsServerHandler;
    @Autowired
    private RedisUtil redisUtil;

    public void start(InetSocketAddress address) throws InterruptedException {
        log.info("正在启动Netty服务，端口={}…", address);
        // 创建主线程组，接收请求
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        // 创建从线程组，处理主线程组分配下来的io操作
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        // 创建netty服务器
        try {
            ServerBootstrap sb = new ServerBootstrap();
            sb.option(ChannelOption.SO_BACKLOG, 1024);
            // 设置主从线程组
            sb.group(bossGroup, workerGroup)
                    // 设置通道
                    .channel(NioServerSocketChannel.class)
                    .localAddress(address)
                    // 子处理器，用于处理workerGroup中的操作。即客户端连接时候触发操作
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            log.info("新连接：{}", ch.localAddress());
                            // 设置log监听器，并且日志级别为debug，方便观察运行流程
                            ch.pipeline().addLast("logging", new LoggingHandler("DEBUG"));
                            // 以下三个是Http的支持
                            // http解码器
                            ch.pipeline().addLast("http-codec", new HttpServerCodec());
                            // http聚合器
                            ch.pipeline().addLast("aggregator", new HttpObjectAggregator(1024 * 1024 * 1024));
                            // 支持写大数据流
                            ch.pipeline().addLast("http-chunked", new ChunkedWriteHandler());
                            // websocket支持,设置路由。设置后会报错。设置后就只有文本消息了
                            //        ch.pipeline().addLast(new WebSocketServerProtocolHandler("/ws", "WebSocket", true, 65536 * 10));
                            // 处理空闲状态的处理器
                            // 三个参数：1.表示多久没有读 会发送一个心跳检测包检测是否链接 2.表示多久没有写 会发送一个心跳检测包检测是否链接 3.多长时间没有读写 会发送一个心跳检测包检测是否链接
                            // 当IdLeStateEvent触发后 会传递给下一个handler处理，通过调用下一个handler的userEventTiggered 在该方法中处理
                            ch.pipeline().addLast("ping", new IdleStateHandler(WsProperties.idleTime, WsProperties.idleTime,
                                    WsProperties.idleTime * 3, TimeUnit.SECONDS));
                            ch.pipeline().addLast(new HeartBeatHandler());
                            // 添加自定义的助手类
                            ch.pipeline().addLast("handler", wsServerHandler);
                        }
                    });
            // 启动server，服务器异步创建绑
            ChannelFuture cf = sb.bind(address).sync();
            // 加入到缓存中
            redisUtil.sSet(RedisConstant.getServerHosts(), WsProperties.localIp + Constant.COLON + WsProperties.httpPort);
            log.info("Netty服务启动完成，正在监听：{}", address, cf.channel().localAddress());
            // 监听关闭channel，关闭服务器通道
            cf.channel().closeFuture().sync();
        } catch (Exception e) {
            log.error("启动Netty服务{}异常", address, e);
        } finally {
            // 释放线程池资源
            bossGroup.shutdownGracefully().sync();
            workerGroup.shutdownGracefully().sync();
        }
    }

    @Override
    public void run() {
        InetSocketAddress address = new InetSocketAddress(WsProperties.wsPort);
        try {
            start(address);
        } catch (InterruptedException e) {
            log.error("Netty启动异常", e);
        }
    }
}
